package v1

import (
	"errors"
	"github.com/sirupsen/logrus"
	"go_blok/server/global"
	"go_blok/server/model"
	"go_blok/server/model/req"
	"go_blok/server/utils/captcha"
	"go_blok/server/utils/email"
	"go_blok/server/utils/pwd"
)

type UserService struct{}

func (s *UserService) Register(req req.RegisterReq) error {
	// 验证邮箱是否与验证码匹配
	_, err := email.Verify(req.Email, req.Code, true)
	if err != nil {
		return errors.New(err.Error())
	}
	// 检查邮箱是否已注册
	var count int64
	global.DB.Model(&model.UserModel{}).Where("email = ?", req.Email).Count(&count)
	if count > 0 {
		return errors.New("注册失败，邮箱已被注册")
	}
	// 密码加密
	hashPwd, err := pwd.GenerateHash(req.Password)
	if err != nil {
		logrus.Errorf("密码加密失败 %s", err)
		return errors.New("密码加密失败")
	}
	// 注册
	newUser := model.UserModel{
		UserName:     req.Email,
		UserPassword: hashPwd,
		Email:        req.Email,
	}
	// 注册
	err = global.DB.Create(&newUser).Error
	if err != nil {
		logrus.Errorf("注册失败 %s", err)
		return errors.New("注册失败")
	}
	return nil
}

func (s *UserService) GetEmailCode(e string) (string, error) {
	// 往注册的邮箱发送验证码
	_, _, answer, err := captcha.GenerateCaptcha()
	if err != nil {
		logrus.Errorf("验证码生成失败 %s", err)
		return "", errors.New("验证码生成失败")
	}
	// 避免重复注册
	email.Set(e, answer)
	// 发送验证码
	err = email.SendEmail("注册验证码", answer, e)
	if err != nil {
		logrus.Errorf("验证码发送失败 %s", err)
		return "", errors.New("验证码发送失败")
	}
	return answer, nil
}
